﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AxeFrog.Composition;

namespace AxeFrog.Web
{
	/// <summary>
	/// Provides static access to the current user context, the current MEF composition container and the
	/// current controller.
	/// </summary>
	public static class RequestContext
	{
		public static BaseController Controller
		{
			get { return Get<BaseController>("Controller"); }
			set { Set("Controller", value); }
		}

		public static ContainerManager Container
		{
			get { return ((WebApplication)HttpContext.Current.ApplicationInstance).Container; }
		}

		//public static T Create<T>()
		//{
		//    try
		//    {
		//        return Container.GetExportedValueOrDefault<T>();
		//    }
		//    catch(CompositionException ex)
		//    {
		//        if(ex.Errors.Count == 1)
		//            throw ex.Errors[0].Exception;
		//        throw;
		//    }
		//}

		//public static List<T> CreateList<T>()
		//{
		//    return Container.GetExportedValues<T>().ToList();
		//}

		//public static T Create<T>(string contractName)
		//{
		//    return Container.GetExportedValue<T>(contractName);
		//}

		public static UserContext CurrentUser
		{
			get
			{
				UserContext uc = Get<UserContext>("UserContext");
				if (uc == null)
				{
					uc = Container.Resolve<UserContext>();
					Set("UserContext", uc);
				}
				return uc;
			}
		}

		private static T Get<T>(string key)
		{
			return (T)HttpContext.Current.Items["AxeFrog.RequestContext." + key];
		}

		private static void Set(string key, object value)
		{
			HttpContext.Current.Items["AxeFrog.RequestContext." + key] = value;
		}
	}
}